package com.mvp.shq.washer.ui.shop.shopcar;

import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import com.jaeger.library.StatusBarUtil;
import com.mvp.shq.washer.R;
import com.mvp.shq.washer.adapter.ShopCarAllListAdapter;
import com.mvp.shq.washer.adapter.ShopcarlistAdapter;
import com.mvp.shq.washer.adapter.ShopcarsetAdapter;
import com.mvp.shq.washer.base.BaseActivity;
import com.mvp.shq.washer.entity.ShopSortType;
import com.mvp.shq.washer.entity.User;
import com.mvp.shq.washer.entity.shop.CollectResponse;
import com.mvp.shq.washer.entity.shop.Product;
import com.mvp.shq.washer.entity.shop.ShopCarMoney;
import com.mvp.shq.washer.entity.shop.TotalOrderList;
import com.mvp.shq.washer.entity.shop.TotalOrderListData;
import com.mvp.shq.washer.entity.shop.result.OrderDataResult;
import com.mvp.shq.washer.entity.shop.result.ProductResult;
import com.mvp.shq.washer.rxbus.BusData;
import com.mvp.shq.washer.rxbus.RxBus;
import com.mvp.shq.washer.rxbus.Subscribe;
import com.mvp.shq.washer.rxbus.ThreadMode;
import com.mvp.shq.washer.ui.shop.productDetail.ProductDetailActivity;
import com.mvp.shq.washer.utils.DBUtil;
import com.mvp.shq.washer.utils.EventCode;
import com.mvp.shq.washer.utils.JumpUtil;
import com.mvp.shq.washer.utils.RecyclerViewDivider;
import com.mvp.shq.washer.utils.SpUtil;
import com.mvp.shq.washer.utils.StringUtils;
import com.mvp.shq.washer.utils.T;
import com.mvp.shq.washer.view.widget.PayTypePopupWindow;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by westing on 2017/10/09.
 */
public class ShopCarActivity extends BaseActivity<Presenter, Model> implements ShopCarConstract.View {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.set)
    TextView set;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.radiochange)
    ImageView radiochange;//全选
    @BindView(R.id.priceyun)
    TextView priceyun;//合计元
    @BindView(R.id.pricefen)
    TextView pricefen;//合计角分
    @BindView(R.id.pricejia)
    TextView pricejia;//合计加号
    @BindView(R.id.priceji)
    TextView priceji;//合计积分
    @BindView(R.id.pricejifen)
    TextView pricejifen;//合计积分文字
    @BindView(R.id.pay)
    Button pay;//支付
    @BindView(R.id.oneview)
    LinearLayout oneview;
    @BindView(R.id.bnt_collect)
    Button bntCollect;//收藏
    @BindView(R.id.bnt_delete)
    Button bntDelete;//删除
    @BindView(R.id.twoview)
    LinearLayout twoview;
    @BindView(R.id.menu_item)
    FloatingActionButton menuItem;
    @BindView(R.id.menu_item1)
    FloatingActionButton menuItem1;
    @BindView(R.id.menu_item2)
    FloatingActionButton menuItem2;
    @BindView(R.id.menu)
    FloatingActionMenu menu;
    @BindView(R.id.recyclerview1)
    RecyclerView recyclerviewSet;
    ShopCarAllListAdapter listAdapter,listAdapter1;
    List<TotalOrderListData> list = new ArrayList<>();
    List<TotalOrderListData> mSumbitOrderList = new ArrayList<>();
    private boolean isCheckedAll;
    private User user;
    @Override
    public int getLayoutId()  {
        return R.layout.activity_shopcar;
    }

    @Override
    public void initView() {
        StatusBarUtil.setColor(this, ContextCompat.getColor(context, R.color.money), 9);
        title.setText("购物车");
        set.setVisibility(View.VISIBLE);
        set.setText("编辑");

        recyclerview.setLayoutManager(new LinearLayoutManager(context));
        RecyclerViewDivider divider = new RecyclerViewDivider(context, LinearLayoutManager.HORIZONTAL, 10, ContextCompat.getColor(context, R.color.gregf8));
        recyclerview.addItemDecoration(divider);

        recyclerviewSet.setLayoutManager(new LinearLayoutManager(context));
        RecyclerViewDivider divider1 = new RecyclerViewDivider(context, LinearLayoutManager.HORIZONTAL, 10, ContextCompat.getColor(context, R.color.gregf8));
        recyclerviewSet.addItemDecoration(divider1);

        list = getProductData();

        listAdapter=new ShopCarAllListAdapter(context,list,allOrderItemOnClick,false);
        recyclerview.setAdapter(listAdapter);
        recyclerview.setVisibility(View.VISIBLE);

        listAdapter1=new ShopCarAllListAdapter(context,list,allOrderItemOnClick,true);
        recyclerviewSet.setAdapter(listAdapter1);
        radiochange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isCheckedAll=!isCheckedAll;
                if(isCheckedAll){
                    radiochange.setBackgroundResource(R.mipmap.cart_selected);
                }else{
                    radiochange.setBackgroundResource(R.mipmap.cart_pressed);
                }
                if (isCheckedAll){
                    for (int i=0;i<list.size();i++){
                        for (int j=0;j<list.get(i).getProducts().size();j++){
                            Product product = list.get(i).getProducts().get(j);
                            if (!product.isCheck()){
                                money += product.getCashPrice()*product.getByNum();
                                integral += product.getIntegralPrice()*product.getByNum();
                                num++;
                                addOrderProduct(product);
                            }
                        }
                    }
                }else {
                    money = 0;
                    integral = 0;
                    num = 0;
                    for (int i=0;i<list.size();i++){
                        for (int j=0;j<list.get(i).getProducts().size();j++){
                            Product product = list.get(i).getProducts().get(j);
                            if (!product.isCheck()){
                                removeOrderProduct(product);
                            }
                        }
                    }
                }
                setMoney();
                listAdapter.setChecking(isCheckedAll);
                listAdapter1.setChecking(isCheckedAll);
                listAdapter.updateUI();
                listAdapter1.updateUI();
            }
        });
        setMoney();
        setUserInfo();
    }

    @Subscribe(code = EventCode.UPDATE_USER)
    public void setUserInfo(){
        user = SpUtil.getUser();
    }

    private ShopCarAllListAdapter.MyAllOrderItemOnClick allOrderItemOnClick=new ShopCarAllListAdapter.MyAllOrderItemOnClick() {
        @Override
        public void onItemOnClick(String productId) {
                //跳转订商品详情
            JumpUtil.toProductDetail(context,productId, ProductDetailActivity.PRODUCT_TYPE_SKU);
        }

    };

    private boolean setLayoutstyle;
    @OnClick({R.id.back,R.id.set, R.id.pay, R.id.bnt_collect, R.id.bnt_delete, R.id.menu_item, R.id.menu_item1, R.id.menu_item2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.set:
                  //编辑和完成
                setLayoutstyle=!setLayoutstyle;
                if(setLayoutstyle){
                    set.setText("完成");
                    recyclerview.setVisibility(View.GONE);
                    recyclerviewSet.setVisibility(View.VISIBLE);
                    twoview.setVisibility(View.VISIBLE);
                    oneview.setVisibility(View.GONE);
                }else{
                    set.setText("编辑");
                    recyclerview.setVisibility(View.VISIBLE);
                    recyclerviewSet.setVisibility(View.GONE);
                    twoview.setVisibility(View.GONE);
                    oneview.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.pay:
                //结算
                if (user == null){
                    JumpUtil.toLogin(context);
                    return;
                }
                //要判断是否选择
                if(mSumbitOrderList.size()!=0) {
                    JumpUtil.toOrderSumbit(context, EventCode.SHOP_PAGETYPE_1);
                }
                //从购物车中删除选中的商品
//                List<Product> delList = new ArrayList<>();
//                for (int i=0;i<list.size();i++){
//                    for (int j=0;j<list.get(i).getProducts().size();j++){
//                        Product product = list.get(i).getProducts().get(j);
//                        if (product.isCheck()){
//                            delList.add(product);
//                        }
//                    }
//                }
//                DBUtil.getInstance().delProductFromCart(delList);
                break;
            case R.id.bnt_collect:
                //收藏
                if (user == null){
                    JumpUtil.toLogin(context);
                    return;
                }
                //要判断是否选择
                List<CollectResponse> collectResponseList = new ArrayList<>();
                String userId = SpUtil.getUser().getId();
                for (int i=0;i<list.size();i++){
                    for (int j=0;j<list.get(i).getProducts().size();j++){
                        Product product = list.get(i).getProducts().get(j);
                        if (product.isCheck()){
                            CollectResponse response = new CollectResponse(product.getProductId(),userId);
                            collectResponseList.add(response);
                        }
                    }
                }
                if(collectResponseList.size()!=0) {
                    presenter.collectProduct(collectResponseList);
                }else {
                    T.show("请先选择商品");
                }
                break;
            case R.id.bnt_delete:
                //删除
                List<Product> products = new ArrayList<>();
                for (int i=0;i<list.size();i++){
                    for (int j=0;j<list.get(i).getProducts().size();j++){
                        Product product = list.get(i).getProducts().get(j);
                        if (product.isCheck()){
                            products.add(product);
                            list.get(i).getProducts().remove(j);
                            j --;
                        }
                    }
                }
                listAdapter.updateUI();
                listAdapter1.updateUI();
                DBUtil.getInstance().delProductFromCart(products);
                break;
            case R.id.menu_item:
                //首页
                JumpUtil.toMall(context);
                menu.close(true);
                break;
            case R.id.menu_item1:
                //购物车
                menu.close(true);
                break;
            case R.id.menu_item2:
                //个人中心
                JumpUtil.toShopUserCenter(context);
                menu.close(true);
                break;
        }
    }

    private List<TotalOrderListData> getProductData(){
        List<TotalOrderListData> list = DBUtil.getInstance().getCompanyProductsInCart();
        Logger.d("商品数量:"+list.size());
        return list;
    }
    @Subscribe(code = EventCode.SHOP_CART_ADD)
    public void addCart(TotalOrderList totalOrderList){
        Logger.d("-------增加数量或者减少");
        list= totalOrderList.getProductResultList();
        listAdapter.setmTotalOrderListData(list);
        listAdapter.updateUIView(totalOrderList.getPosition());
        listAdapter1.setmTotalOrderListData(list);
        listAdapter1.updateUIView(totalOrderList.getPosition());
        setMoney();
    }

    @Subscribe(code = EventCode.SHOP_CART_DEL_PRODUCT)
    public void delProduct(TotalOrderList totalOrderList){
        Logger.d("-------增加数量或者减少");
        list= totalOrderList.getProductResultList();
        listAdapter.setmTotalOrderListData(list);
        listAdapter.updateUIView(totalOrderList.getPosition());
        listAdapter1.setmTotalOrderListData(list);
        listAdapter1.updateUIView(totalOrderList.getPosition());
        removeOrderProductList(totalOrderList);
    }

    public void delProductList(List<TotalOrderListData> setOrderList){
        for(int i=0,len=list.size();i<len;i++){
            for (int j=0,lens=setOrderList.size();j<lens;j++){
                if(setOrderList.get(j).getCompanyId().equals(list.get(i).getCompanyId())){
                    for(int z=0,lenz=setOrderList.get(j).getProducts().size();z<lenz;z++){
                        //计算金钱
                        Product  product= setOrderList.get(j).getProducts().get(z);
                        money -= product.getCashPrice()*product.getByNum();
                        if(money<0){
                            money=0;
                        }
                        integral -= product.getIntegralPrice()*product.getByNum();
                        if(integral<0){
                            integral=0;
                        }
                        num--;
                        if(num<0){
                            num=0;
                        }
                    }
                    //原始列表
                    list.remove(i);
                    setOrderList.remove(j);

                }
            }
        }
        Logger.d("-------删除前："+mSumbitOrderList.size());
        mSumbitOrderList=setOrderList;
        Logger.d("----  ---删除后："+list.size());
        listAdapter.setmTotalOrderListData(list);
        listAdapter1.setmTotalOrderListData(list);
        listAdapter.updateUI();
        listAdapter1.updateUI();
        setMoney();
        radiochange.setBackgroundResource(R.mipmap.cart_pressed);
    }


    private void removeOrderProductList(TotalOrderList totalOrderList){

        for (int i=0,len=totalOrderList.getProductResultList().size();i<len;i++){

            TotalOrderListData totalOrderListData=totalOrderList.getProductResultList().get(i);

            for (int j=0,lens=totalOrderListData.getProducts().size();j<lens;j++) {

                Product product=totalOrderListData.getProducts().get(j);
                if (product.getCompanyId().equals(mSumbitOrderList.get(i).getCompanyId())) {
                    delete(product);
                }
            }
        }
    }
    private void delete(Product product){
        money -= product.getCashPrice()*product.getByNum();
        if(money<0){
            money=0;
        }
        integral -= product.getIntegralPrice()*product.getByNum();
        if(integral<0){
            integral=0;
        }
        num--;
        if(num<0){
            num=0;
        }
        removeOrderProduct(product);
        setMoney();

    }

    private double money=0;//金额
    private int integral=0;//积分
    private int num=0;//数量


    @Subscribe(code = EventCode.SHOP_CART_CHECK)
    public void check(Product product){
        Logger.d("-------选中");
        money += product.getCashPrice()*product.getByNum();
        integral += product.getIntegralPrice()*product.getByNum();
        num++;
        addOrderProduct(product);
        setMoney();
    }
    @Subscribe(code = EventCode.SHOP_CART_CHECKNO)
    public void checkNo(Product product){
        Logger.d("-------不选中");
        money -= product.getCashPrice()*product.getByNum();
        if(money<0){
            money=0;
        }
        integral -= product.getIntegralPrice()*product.getByNum();
        if(integral<0){
            integral=0;
        }
        num--;
        if(num<0){
            num=0;
        }
        isCheckedAll = false;
        radiochange.setBackgroundResource(R.mipmap.cart_pressed);
        removeOrderProduct(product);
        setMoney();
    }
    @Subscribe(code = EventCode.SHOP_CART_UPDATE_COMPANY_LIST)
    public void updateCompanyList(BusData data){
        int position = data.getPosition();
        Logger.d("刷新item："+position);
        listAdapter.updateCompanyList(position);
        listAdapter1.updateCompanyList(position);
    }

    @Subscribe(code = EventCode.SHOP_CART_UPDATE_PRODUCT)
    public void updateProduct(TotalOrderList totalOrderList){
        Logger.d("-------更新");
        list= totalOrderList.getProductResultList();
        listAdapter.setmTotalOrderListData(list);
        listAdapter.updateUIView(totalOrderList.getPosition());
        listAdapter1.setmTotalOrderListData(list);
        listAdapter1.updateUIView(totalOrderList.getPosition());
    }

    private void addOrderProduct(Product product){
        for (int i=0,len=mSumbitOrderList.size();i<len;i++){
            if(product.getCompanyId().equals(mSumbitOrderList.get(i).getCompanyId())){
                mSumbitOrderList.get(i).getProducts().add(product);
                return;
            }
        }
        List<Product> productList= new ArrayList<Product>();
        productList.add(product);
        mSumbitOrderList.add(new TotalOrderListData(product.getCompanyId(),productList));
    }
    private void removeOrderProduct(Product product){
        for (int i=0,len=mSumbitOrderList.size();i<len;i++){
            if(product.getCompanyId().equals(mSumbitOrderList.get(i).getCompanyId())){
                mSumbitOrderList.get(i).getProducts().remove(product);
                return;
            }
        }
    }

    private void setMoney(){
       pricejia.setVisibility(View.VISIBLE);
        priceyun.setVisibility(View.VISIBLE);
        pricefen.setVisibility(View.VISIBLE);
        priceji.setVisibility(View.VISIBLE);
        pricejifen.setText("积分");

        pay.setText("结算("+num+")");
        priceyun.setText(""+(int)money);//合计元
        pricefen.setText(StringUtils.BigDecimalToStr(BigDecimal.valueOf(money)));//合计角分
        priceji.setText(""+integral);//合计积分
        if(money == 0 && integral != 0){
            pricejia.setVisibility(View.GONE);
            priceyun.setVisibility(View.GONE);
            pricefen.setVisibility(View.GONE);
        }else if(integral==0){
            pricejia.setVisibility(View.GONE);
            pricejifen.setText("");
            priceji.setVisibility(View.GONE);
        }
    }
    @Subscribe(code = EventCode.SHOP_SEND_PRODUCT_ON_SHOPCAR)
    public void sendProduct(){
        Logger.d("提交订单：----"+mSumbitOrderList.size());
        if(mSumbitOrderList.size()!=0){
            RxBus.get().send(EventCode.SHOP_SUMBIT_ORDER,new TotalOrderList(mSumbitOrderList));
        }
    }
    @Subscribe(code = EventCode.SHOP_PAY_SUCCESS)
    public void paySuccess(){
        finish();
    }

    @Override
    public void collectProductS() {
        T.show("收藏成功");
    }
}
